﻿using Biotech.Utils;
using project.B12.IService;
using project.B12.Model.BaseModel;
using project.B12.Model.Common;
using project.B12.Model.Enums;
using project.B12.Model.Models;
using software.Common.MVVM;
using software.dll.user;
using System.Collections.ObjectModel;
using System.Xml.Linq;

namespace project.B12.Service.UserService
{
    public partial class UserService : ObservableObject, IUserService
    {
        #region Model
        private string search_UserName = string.Empty;//用户设置搜索条件(用户名称)
        public string Search_UserName
        {
            get { return search_UserName; }
            set { search_UserName = value; this.RaisePropertyChanged(); }
        }
        private ObservableCollection<UserModel> userList;//用户清单
        public ObservableCollection<UserModel> UserList
        {
            get { return userList; }
            set { userList = value; RaisePropertyChanged(); }
        }
        #endregion

        #region Method
        /// <summary>
        /// 获取所有用户清单
        /// 按角色等级进行筛选并排序
        /// </summary>
        /// <returns></returns>
        public (MessageModel, ObservableCollection<UserModel>) GetAllUsers()
        {
            try
            {
                List<UserModel> temp=new List<UserModel>();
                //当前已登录账户校色是否为厂家或超管？
                if (IsAdmin())
                {
                    temp = _userManager.ShowUser().Where(e=>e.Name.Contains(Search_UserName)).ToList();//是，获取所有账号
                }
                else
                {
                    temp = _userManager.GetDepartmentUser(CurrentUser.Department).Where(e => e.Name.Contains(Search_UserName)).ToList();//否，获取所在同部门下的账号
                }
                UserList = new ObservableCollection<UserModel>(FilterateOrderByRoleName(temp));
                return (MessageModel.ReturnSuccess(), UserList);//成功
            }
            catch(Exception ex)
            {
                return (MessageModel.ReturnFail(ex.ToString()), new ObservableCollection<UserModel>());//失败
            }
        }

        /// <summary>
        /// 筛选用户清单并排序
        /// 根据当前已登录用户的角色截取用户清单
        /// 例如超级管理员只能看见比自己等级小的角色信息（管理员、普通用户）
        /// </summary>
        public List<UserModel> FilterateOrderByRoleName(List<UserModel> userModels)
        {
            //使用 LINQ 筛选在 result 中出现的元素
            var result1 = userModels.Where(item => RoleLists.Any(item2 => item2.Value.ToString() == item.RoleName)).ToList();
            foreach (var item in result1)//将角色名翻译成对应线程语言
            {
                foreach (var item1 in RoleLists)
                {
                    if (item1.Value.ToString() ==  item.RoleName)
                    {
                        item.RoleName = EnumUtil.GetEnumDisplay(item1.Value);
                    }
                }
            }
            // 使用 LINQ 按照 result 中的顺序排序 userModels
            return result1.OrderBy(item => GetEnumIndex(item.RoleName)).ToList();
        }

        /// <summary>
        /// 获取角色枚举所在的索引号
        /// </summary>
        /// <param name="_rolename"></param>
        /// <returns></returns>
        private uint GetEnumIndex(string _rolename)
        {
            foreach (var item in RoleLists) 
            {
                if (item.Value.ToString() == _rolename)
                {
                    return (uint)item.Value;
                }
            }
            return 0;
        }

        /// <summary>
        /// 重置用户清单界面
        /// </summary>
        public MessageModel ResetUsersList()
        {
            try
            {
                Search_UserName = string.Empty;//搜索条件置空
                GetAllUsers();//刷新清单
                return MessageModel.ReturnSuccess();//成功
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }

        /// <summary>
        /// 变更账户可用性状态
        /// </summary>
        /// <param name="name"></param>
        public MessageModel ChangeLockedState(UserModel name)
        {
            try
            {
                if (GetUserRight(RightEnum.UserManagerUsability))
                {
                    var flag = _userManager.UpdateUserLock(name.Name, !name.IsLocked);
                    if (flag)
                    {
                        GetAllUsers();
                        return MessageModel.ReturnSuccess();//成功
                    }
                    else
                        return MessageModel.ReturnFail("User status change failed");//失败
                }
                else
                    return MessageModel.ReturnFail("The user has insufficient permissions!");//失败
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }

        /// <summary>
        /// 用户是否有权限
        /// </summary>
        /// <param name="name"></param>
        /// <param name="rightEnum"></param>
        /// <returns></returns>
        public bool GetUserRight(RightEnum rightEnum)
        {
            if (IsAdmin())
                return true;
            else
                return _userManager.GetUserRight(CurrentUser.Name, (int)rightEnum);
        }

        /// <summary>
        /// 检查密码是否合规
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public MessageModel CheckPassword(string password)
        {
            try
            {
                _userManager.CheckPassword(password);
                return MessageModel.ReturnSuccess();//成功
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }

        /// <summary>
        /// 更新用户(密码)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public MessageModel UpdateUser(string name, string password)
        {
            try
            {
                _userManager.UpdateUserPassword(name, password);
                return MessageModel.ReturnSuccess();
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }

        /// <summary>
        /// 更新用户(过期时间)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public MessageModel UpdateExpirationTime(string name, ExpirationTimeEnum? newUserExpirationTime)
        {
            try
            {
                if (newUserExpirationTime != ExpirationTimeEnum.不过期)
                    _userManager.UpdateUserExpirationTime(name, DateTime.Now.AddDays((int)newUserExpirationTime));
                else
                    _userManager.UpdateUserExpirationTime(name, DateTime.MinValue);
                GetAllUsers();
                return MessageModel.ReturnSuccess();
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }

        /// <summary>
        /// 根据用户名删除用户
        /// </summary>
        /// <param name="pUserName"></param>
        /// <returns></returns>
        public MessageModel DeleteUser(string pUserName)
        {
            try
            {

                if (!_userManager.GetUser(pUserName))
                    return MessageModel.ReturnFail("Failed to delete user, user does not exist.");
                _userManager.DeleteUser(pUserName);
                GetAllUsers();
                return MessageModel.ReturnSuccess();
            }
            catch (Exception ex)
            {
                return MessageModel.ReturnFail(ex.ToString());//失败
            }
        }
        #endregion
    }
}
